package com.nongcai159.mall.lib_common.utils.imageloader.transformation;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.util.Util;

import java.security.MessageDigest;

public class RoundCornerBorderTransformation extends BitmapTransformation {
    private final String ID = getClass().getName();

    private Paint borderPaint = null;
    private float radius;
    private float borderWidth;

    public RoundCornerBorderTransformation(float radius) {
        this.radius = radius;
    }

    public RoundCornerBorderTransformation(float radius, float borderWidth, int borderColor) {
        this.radius = radius;
        this.borderWidth = borderWidth;

        if (borderWidth <= 0) {
            return;
        }
        borderPaint = new Paint();
        borderPaint.setAntiAlias(true);
        borderPaint.setDither(true);
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setColor(borderColor);
        borderPaint.setStrokeWidth(borderWidth);
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        int width = toTransform.getWidth();
        int height = toTransform.getHeight();

        Bitmap bitmap = pool.get(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setHasAlpha(true);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(toTransform, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        canvas.drawRoundRect(new RectF(0, 0, width, height), radius, radius, paint);
        if (borderPaint != null && borderWidth > 0) {
            float offset = borderWidth / 2;
            canvas.drawRoundRect(new RectF(offset, offset, width - offset, height - offset),
                    radius, radius, borderPaint);
        }
        return bitmap;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof RoundCornerBorderTransformation) {
            RoundCornerBorderTransformation other = (RoundCornerBorderTransformation) obj;
            return radius == other.radius;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Util.hashCode(ID.hashCode(), Util.hashCode(radius));
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        messageDigest.update((ID + radius).getBytes(CHARSET));
    }
}
